<?php
///
namespace lxsphp\Core;

///
use lxsphp\App;

/**
 * 核心 - [日志]类
 *
 * @version $Id: Log.php 175 2014-07-16 10:21:58Z linsir123 $
 * @package lxsphp\Core
 */
class Log
{
	/**
	 * 配置
	 *
	 * @var array
	 */
	public $conf = array();

	/**
	 * 构造函数
	 */
	public function __construct()
	{
		///
		$this->conf = App::o("app.log");
	}

	/**
	 * 写日志
	 *
	 * @param mixed $content 日志内容
	 * @param string $relativePath 相对路径
	 * @param null $rootPath 绝对路径
	 */
	public function write($content, $relativePath = 'tmp', $rootPath = null)
	{
		///
		$o = App::$I->getRequest();
		$ip = $o->getIp();
		$route = $o->route;
		$time = date('Y-m-d H:i:s');
		$method = $_SERVER['REQUEST_METHOD'];
		$content = is_string($content) ? $content : var_export($content, true);
		$content = sprintf("%s - %s - \"%s /%s\" %s \r\n",
			$time,
			$ip,
			$method,
			$route,
			$content);

		///
		App::$I->getHook()->activeHook(
			'Log', array(
			$content,
			$relativePath
		));

		///
		$file = $this->_getFile($relativePath, $rootPath);
		$this->_save($file, $content);
	}

	/**
	 * 级联创建目录
	 *
	 * @param string $path 待处理的目录
	 * @param int $mode 创建模式
	 *
	 * @return bool
	 */
	public function mkdir(& $path, $mode = 0777)
	{
		///
		$tmp = substr($path, - 1);
		if ($tmp == "\\" || $tmp == "/")
			$path = substr($path, 0, - 1);

		if (file_exists($path) && is_dir($path))
			return true;

		///
		$flag = $this->mkdir(dirname($path), $mode);
		if (empty($flag))
			return false;

		///
		return mkdir($path) ? chmod($path, $mode) : false;
	}

	/**
	 * 取得日志文件路径
	 *
	 * @param string $relativePath
	 * @param string $rootPath
	 *
	 * @return string
	 */
	private function _getFile($relativePath, $rootPath = null)
	{
		if (empty($rootPath))
			$rootPath = CACHE_DIR;

		///
		$path = $rootPath . $relativePath;
		$this->mkdir($path);

		///
		return sprintf("%s/log.%s.txt", $path, date("Y_m_d"));
	}

	/**
	 * 保存文件
	 *
	 * @param string $file
	 * @param string $content
	 */
	private function _save($file, $content)
	{
		$mode = 'a+';
		$maxSize = intval($this->conf['maxSize']);

		///
		if ($fp = @fopen($file, $mode)) {
			if ($maxSize > 0 && filesize($file) > $maxSize) {
				$tmp = array(time(), basename($file));
				$file2 = dirname($file) . '/' . implode('_', $tmp);

				///
				@fclose($fp);
				@rename($file, $file2);
				$fp = @fopen($file, 'w');
			}

			///
			@fwrite($fp, $content);
			@fclose($fp);
		}
	}
}
